<template>
  <div class="h-full">
    <div class="w-full text-center mb-2">
      主题：<TreeSelect
        showSearch
        style="width: 200px"
        :tree-data="themeTypeOptions"
        v-model:value="selected"
        @change="selectedChange"
      />
      <a-button type="primary" class="ml-2" @click="handleSubmit">确定</a-button>
      <a-button type="primary" class="ml-2" @click="handleRun">运行</a-button>
      <a-button type="primary" class="ml-2" @click="handleClose">关闭</a-button>
    </div>
    <div class="h-full">
      <AceEditor v-model:value="script" style="height: 100%" ref="aceEditorRef" />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, watch, defineExpose, nextTick } from 'vue';
  import { TreeSelect } from 'ant-design-vue';
  import { themeTypeOptions } from './aceEditView.data';
  import { getFlowRunScript } from '/@/api/flowManage/flowManage';
  import { AceEditor } from '/@/components/AceEditor/index';
  import { useRouter } from 'vue-router';
  import { getToken } from '/@/utils/auth';
  const emits = defineEmits(['close', 'success']);
  const handleClose = () => {
    emits('close');
  };
  const props = defineProps({
    scriptStr: {
      type: String,
      default: '',
    },
  });
  watch(
    () => props.scriptStr,
    async (newVal) => {
      await nextTick();
      script.value = newVal;
    },
    {
      immediate: true,
    },
  );
  const aceEditorRef = ref<Nullable<HTMLElement>>(null);
  const selected = ref('chrome');
  const script = ref('');
  const handleSubmit = () => {
    emits('success', unref(script));
  };

  const selectedChange = (value) => {
    unref(aceEditorRef).setTheme(value);
  };
  //插入值
  const insertScript = (script) => {
    if (unref(aceEditorRef)) {
      unref(aceEditorRef)?.insertScript(script);
    }
  };

  defineExpose({
    insertScript,
  });

  const { resolve } = useRouter();
  const handleRun = async () => {
    const res = await getFlowRunScript({ script: unref(script) });
    let routeUrl: any = {};
    routeUrl = resolve({
      path: '/runScript',
      query: {
        result: res.result,
        token: getToken() as any,
      },
    });
    // + "screenx=" + xposition + ","                       //仅适用于Netscape
    // + "screeny=" + yposition + ","                       //仅适用于Netscape
    // + "left=" + xposition + ","                      //IE
    // + "top=" + yposition;                                //IE
    const height = 400;
    const width = 450;
    const top = (window.screen.height - 30 - height) / 2; //获得窗口的垂直位置;
    // const left = (window.screen.width - 10 - width) / 2; //获得窗口的水平位置;//不生效
    const left = (window.screenX || window.screenLeft || 0) + (screen.width - width) / 2; //获得窗口的水平位置;
    window.open(
      routeUrl.href,
      '',
      `height=${height},width=${width},top=${top}, left=${left},screenx=${left},screeny=${top},alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
    );
  };
</script>
